package com.ocean.business.service.impl;

import com.ocean.business.domain.DownTotalDo;
import com.ocean.business.domain.ProductReportDo;
import com.ocean.business.domain.UploadingTotalDo;
import com.ocean.business.domain.query.DownTotalQuery;
import com.ocean.business.domain.query.UploadStatisticsParticularsQuery;
import com.ocean.business.mapper.BusinessStatisticsMapper;
import com.ocean.business.service.IBusinessStatisticsService;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: FuGui Wang
 * @Description: 后台系统-统计管理 service interface impl
 * @Date 2022/12/5
 * @Version V1.1.0
 */
@Service
public class BusinessStatisticsServiceImpl implements IBusinessStatisticsService {

    @Autowired
    private BusinessStatisticsMapper statisticsMapper;

    /**
     * 统计管理-按下载量统计列表
     * @param query 检索条件
     * @return 数据集合
     */
    @Override
    public List<DownTotalDo> selectDownloadStatisticsList(DownTotalQuery query) {
        // 查询数据列表
        List<DownTotalDo> downTotalDos = statisticsMapper.selectDownloadStatisticsList(query);
        // 为列表设置序号id
        if(null != downTotalDos && downTotalDos.size() > 0){
            Integer i = 1;
            for (DownTotalDo downTotalDo : downTotalDos) {
                downTotalDo.setId(i);
                i++;
            }
        }
        return downTotalDos;
    }

    /**
     * 统计管理-产品上传统计
     * @param query 检索条件
     * @return 返回数据集合
     */
   /* @Override
    public List<UploadingTotalDo> selectUploadingStatisticsList(DownTotalQuery query) {
        // 查询数据列表
        List<UploadingTotalDo> uploadingTotalDos = statisticsMapper.selectUploadingStatisticsList(query);
        // 为列表设置序号id
        if(null != uploadingTotalDos && uploadingTotalDos.size() > 0){
            Integer i = 1;
            for (UploadingTotalDo uploadingTotalDo : uploadingTotalDos) {
                uploadingTotalDo.setId(String.valueOf(i));
                i++;
            }
        }
        return uploadingTotalDos;
    }*/
    @Override
    public List<UploadingTotalDo> selectUploadingStatisticsList(DownTotalQuery query) {
        //返回的数据
        List<UploadingTotalDo> list = new LinkedList<>();
        // 查询产品列表
        List<UploadingTotalDo> uploadingTotalDos = statisticsMapper.selecplist(query);
        String beginTime = (String) query.getParams().get("beginTime");
        String endTime = (String) query.getParams().get("endTime");
        //循环产品列表
        for (UploadingTotalDo uploadingTotalDo : uploadingTotalDos) {
            int num1 = statisticsMapper.selenum(uploadingTotalDo.getId(), "1", uploadingTotalDo.getProductName(), beginTime, endTime, uploadingTotalDo.getDeptName());//数量查询要根据query里的参数进行查询
            int num2 = statisticsMapper.selenum(uploadingTotalDo.getId(), "2", uploadingTotalDo.getProductName(), beginTime, endTime, uploadingTotalDo.getDeptName());//单位
            /*int num3 = statisticsMapper.selenum(uploadingTotalDo.getId(),"3");*/
            int num0 = statisticsMapper.selenum(uploadingTotalDo.getId(), "0", uploadingTotalDo.getProductName(), beginTime, endTime, uploadingTotalDo.getDeptName());
            uploadingTotalDo.setShouldUpload(uploadingTotalDo.getFrequency());//应上传(值为每天应上传几个 03 是两个 其他是1个)
            uploadingTotalDo.setRealityUpload(num1 + num2);//实上传
            uploadingTotalDo.setNormalUpload(num1);//正常上传
            uploadingTotalDo.setLateUpload(num2);//晚传上传
            /*uploadingTotalDo.setRepairUpload(num3);//补传上传*/
            uploadingTotalDo.setLeakUpload(num0);//异常上传
            list.add(uploadingTotalDo);
        }
 /*       list.sort((p1, p2) -> Integer.compare(p2.getLeakUpload(), p1.getLeakUpload()));

        // 或者使用Comparator的静态方法和reversed()
        list.sort(Comparator.comparingInt(UploadingTotalDo::getLeakUpload).reversed());

        // 输出排序后的列表
        for (UploadingTotalDo person : list) {
            System.out.println(person.getDeptName() + " - " + person.getLeakUpload());
        }*/

        return list;
    }
    /**
     * 统计管理-导出-详情
     * @param query 检索条件
     * @return 数据集合
     */
    @Override
    public List<ProductReportDo> selectUploadingParticularsList(DownTotalQuery query) {
        // 查询数据列表
        List<ProductReportDo> productReportDos = statisticsMapper.selectUploadingParticularsList(query);
        // 为列表设置序号id
        if(null != productReportDos && productReportDos.size() > 0){
            Integer i = 1;
            for (ProductReportDo uploadingTotalDo : productReportDos) {
                uploadingTotalDo.setId(String.valueOf(i));
                i++;
            }
        }
        // 转换 “状态” 字段数据
        if(null != productReportDos && productReportDos.size() > 0){
            for (ProductReportDo productReportDo : productReportDos) {
                // 活跃状态（1：正常；2：晚传；3：补传；0：异常）
                productReportDo.setStatus("1".equals(productReportDo.getStatus()) ? "正常" : "2".equals(productReportDo.getStatus()) ? "晚传" : "3".equals(productReportDo.getStatus()) ? "补传" : "0".equals(productReportDo.getStatus()) ? "异常":"");
            }
        }
        return productReportDos;
    }

    /**
     * 统计管理-查看详情
     * @param query 检索条件
     * @return 数据集合
     */
    @Override
    public List<ProductReportDo> viewParticulars(UploadStatisticsParticularsQuery query) {
        return statisticsMapper.viewParticulars(query);
    }

    @Override
    public int selectnum(DownTotalQuery query) {
        List<UploadingTotalDo> uploadingTotalDos = statisticsMapper.selecplist(query);
        return uploadingTotalDos.size();
    }

    @Override
    public List<Double> getzsize() {
        return statisticsMapper.getzsize();
    }

    @Override
    public byte[] replacePlaceholders(InputStream inputStream, Map<String, String> replacements) throws IOException {
        try (XWPFDocument document = new XWPFDocument(inputStream)) {
            // 替换正文中的占位符
            replaceInParagraphs(document.getParagraphs(), replacements);

            // 替换表格中的占位符
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        replaceInParagraphs(cell.getParagraphs(), replacements);
                    }
                }
            }

            // 替换页眉中的占位符
            for (XWPFHeader header : document.getHeaderList()) {
                replaceInParagraphs(header.getParagraphs(), replacements);
            }

            // 替换页脚中的占位符
            for (XWPFFooter footer : document.getFooterList()) {
                replaceInParagraphs(footer.getParagraphs(), replacements);
            }

            // 保存到字节数组
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                document.write(out);
                return out.toByteArray();
            }
        }
    }
    private void replaceInParagraphs(List<XWPFParagraph> paragraphs, Map<String, String> replacements) {
        for (XWPFParagraph paragraph : paragraphs) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null) {
                    for (Map.Entry<String, String> entry : replacements.entrySet()) {
                        if (text.contains(entry.getKey())) {
                            text = text.replace(entry.getKey(), entry.getValue());
                            run.setText(text, 0);
                        }
                    }
                }
            }
        }
    }

}
